package com.hexb.core.model;

import com.hexb.core.utils.ValueEnumUtils;
import org.apache.ibatis.type.Alias;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@Alias("enumValueTypeHandler")
@SuppressWarnings("unused")
public class EnumValueTypeHandler<E extends Enum<E> & ValueEnum<E>> extends BaseTypeHandler<ValueEnum> {

    private Class<ValueEnum> type ;

    public EnumValueTypeHandler() {
    }

    public EnumValueTypeHandler(Class<ValueEnum> type) {
        if(null == type){
            throw new IllegalArgumentException("类型参数不能为空");
        }
        this.type = type ;
    }

    private ValueEnum convert(int value){
        return ValueEnumUtils.getEnumByValue(type,value);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, ValueEnum valueEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i,valueEnum.getValue());
    }

    @Override
    public ValueEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return convert(resultSet.getInt(s));
    }

    @Override
    public ValueEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return convert(resultSet.getInt(i));
    }

    @Override
    public ValueEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return convert(callableStatement.getInt(i));
    }
}
